﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
namespace HtmlPictureHelper.Utility
{
    public class WebDownloadUtility
    {
        public static int WebClientInstanceCount => 24;

        /// <summary>
        /// 单张图片下载
        /// </summary>
        /// <param name="pictureUrl">图片地址</param>
        /// <param name="saveFileName">保存文件名</param>
        /// <param name="downloadCompeletedCallback">下载完成回调</param>
        /// <param name="progressChangeCallback">下载进度改变回调</param>
        public static void DownloadSinglePicture(string pictureUrl,string saveFileName, AsyncCompletedEventHandler downloadCompeletedCallback =null,DownloadProgressChangedEventHandler progressChangeCallback=null)
        {
            if(string.IsNullOrEmpty(pictureUrl) || string.IsNullOrEmpty(saveFileName))
            {
                return;
            }
            using (WebClient client = new WebClient())
            {
                if(downloadCompeletedCallback !=null)
                {
                    client.DownloadFileCompleted += downloadCompeletedCallback;
                }
                if(progressChangeCallback !=null)
                {
                    client.DownloadProgressChanged += progressChangeCallback;
                }
                client.DownloadFileAsync(new Uri(pictureUrl), saveFileName);
            }
        }
        /// <summary>
        /// 下载经过图片分析器分析后的图片
        /// </summary>
        /// <param name="model">图片分析模型</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="downloadCompeletedCallback">下载完成回调</param>
        /// <param name="progressChangeCallback">下载进度改变回调</param>
        public async static void DownloadAnalyzedPicture(Model.AnalyzedPictureModel model,string savePath, Func<Model.DownloadAnalyzedPictureCompeletedEventArgs,int> downloadCompeletedCallback = null, ProgressChangedEventHandler progressChangeCallback = null)
        {
            if(model == null || string.IsNullOrEmpty(savePath))
            {
                return;
            }
            int pictureCount = model.PictureLinks.Count;
            string fileName = "";
            long totalBytes = 0;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i=0;i<pictureCount;)
            {
                //指定多个WebClient示例，并发下载
                for(int j=0;j<WebClientInstanceCount && i<pictureCount;j++,i++)
                {
                    using (WebClient client = new WebClient())
                    {
                        //在每张图片的下载进度改变事件中统计接受总字节数
                        client.DownloadProgressChanged += (s, e) =>
                        {
                            totalBytes += e.BytesReceived;
                        };
                        //发布下载进度改变事件
                        int percentage = (int)Math.Ceiling((i / (decimal)pictureCount) * 100);
                        progressChangeCallback?.Invoke(null, new ProgressChangedEventArgs(percentage, i));
                        fileName = System.IO.Path.GetFileName(model.PictureLinks[i].OriginalString);
                        try
                        {
                            await client.DownloadFileTaskAsync(model.PictureLinks[i], Path.Combine(savePath, fileName));
                        }
                        catch (System.Net.WebException excpetion)
                        {
                            
                        }
                        
                    }
                }
            }
            watch.Stop();
            //计算下载总用时
            long totalMilliseconds = watch.ElapsedMilliseconds;
            //批量下载完成，发布下载完成事件
            downloadCompeletedCallback?.Invoke(new Model.DownloadAnalyzedPictureCompeletedEventArgs()
            {
                PictureCount = pictureCount,
                TotalBytesCount = totalBytes,
                TotalMilliseconds = totalMilliseconds
            });
        }
    }
}
